package org.pvt.gui;

import android.database.Cursor;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.LinearLayout;
import android.widget.TextView;
import org.jetbrains.annotations.NotNull;
import org.pvt.R;
import org.pvt.model.Models;
import org.pvt.model.Queries;
import org.pvt.model.data.IdAndNameDTO;
import org.pvt.model.db.DBUtils;

import java.util.List;

import static org.pvt.gui.UIUtils.floatToText;

/**
 * @author Pavel Talanov
 */
public final class BalanceActivity extends ActivityWithMainMenu {
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.balance);
        List<IdAndNameDTO> idToName = Queries.getIdToName(Models.Person, getEventId(), this);
        for (IdAndNameDTO idAndName : idToName) {
            float balance = queryBalance(idAndName.id);
            createView(idAndName.name, balance);
        }
    }

    private void createView(@NotNull String name, float balance) {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        LinearLayout balanceEntryView = (LinearLayout) layoutInflater.inflate(R.layout.balance_entry, null);
        TextView balanceAmount = (TextView) balanceEntryView.findViewById(R.id.balanceAmount);
        balanceAmount.setText(floatToText(balance, true));
        TextView personName = (TextView) balanceEntryView.findViewById(R.id.balancePerson);
        personName.setText(name);
        LinearLayout balanceLayout = (LinearLayout) findViewById(R.id.balanceLayout);
        balanceLayout.addView(balanceEntryView);
    }

    private float queryBalance(long id) {
        Cursor cursor = DBUtils.getReadableDB(this).rawQuery(
                "SELECT SUM(amount - must_pay) " +
                        "FROM payment " +
                        "INNER JOIN " +
                        "( " +
                        "SELECT expenses_id AS e_i, AVG(amount) AS must_pay " +
                        "FROM payment " +
                        "GROUP BY expenses_id " +
                        ") " +
                        "AS A " +
                        "ON ( payment.expenses_id = A.e_i ) " +
                        "WHERE payment.persons_id = " + id,
                new String[]{});
        cursor.moveToFirst();
        float result = cursor.getFloat(0);
        cursor.close();
        return result;
    }


    protected long getEventId() {
        return getIntent().getExtras().getLong(Models.Event.getExtrasName());
    }
}